import re
from django.http import JsonResponse
from utils.response import json_response_unauthorized


class HeaderAuthMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # 使用正则表达式精确匹配路径
        self.exempt_paths = [
            re.compile(r'^/api/login/?$'),
            re.compile(r'^/api/register/?$'),
            re.compile(r'^/admin/'),
            re.compile(r'^/$'),
            re.compile(r'^/static/.*$'),  # 放行所有静态文件
            re.compile(r'^/media/.*$'),   # 放行所有媒体文件
            re.compile(r'^.*\.(jpg|jpeg|png|gif|bmp|webp|svg|ico)$', re.I),  # 图片
            re.compile(r'^.*\.(mp4|webm|ogg|mov|avi|flv)$', re.I),  # 视频
            re.compile(r'^.*\.(mp3|wav|ogg|flac|aac)$', re.I),  # 音频
            re.compile(r'^.*\.(js|css|json|xml|txt|pdf)$', re.I),  # 其他静态资源
        ]
        self.required_headers = {'token': r'^\d+\.\d+\.\d+$'}

    def __call__(self, request):
        # 调试输出
        print(f"Request path: {request.path}")

        # 放行OPTIONS预检请求
        if request.method == 'OPTIONS':
            return self.get_response(request)

        # 检查豁免路径
        if not self._path_requires_auth(request.path):
            print(f"Path {request.path} is exempt from auth")
            return self.get_response(request)

        # 验证token
        token = request.headers.get('token')
        print(f"Token received: {token}")

        if not token:
            return json_response_unauthorized(message='Missing token header', code=4001)

        if not re.match(self.required_headers['token'], token):
            return json_response_unauthorized(message='Invalid token format', code=4002)

        return self.get_response(request)

    def _path_requires_auth(self, path):
        # 统一路径格式
        path = path.rstrip('/') + '/'  # 确保路径以/结尾
        # 检查是否是静态资源请求
        return not any(pattern.fullmatch(path) for pattern in self.exempt_paths)